package com.cq.androidtools.text

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.widget.TextView

/**
 * 作者: CQ
 * 日期: 2022-07-12
 * 说明:
 */
@SuppressLint("AppCompatCustomView")
class TextViewNovel @JvmOverloads constructor(
    context : Context, attrs : AttributeSet? = null, defStyleAttr : Int = 0
) : TextView(context, attrs, defStyleAttr) {




    fun initDate(data : String) {
        text = data
        post {
            getPageData()
        }
    }

    fun getPageData() : MutableList<String>{

        val list = mutableListOf<String>()

        // 获取第一页行数作为每页显示行数
        val lineNum1 = getLineNum()

        while (getLineNum() >= lineNum1) {
            val line = getLineNum()
            val content = text.subSequence(0, getCharNum(line))
            list.add(content.toString())
            text = text.subSequence(getCharNum(line), text.length)
        }

        return list
    }

    override fun onLayout(changed : Boolean, left : Int, top : Int, right : Int, bottom : Int) {
        super.onLayout(changed, left, top, right, bottom)
        reSize()
    }

    fun reSize() : Int{
        val oldContent = text
        val size = getCharNum()
        Log.e("TextViewNovel", "getCharNum = $size")
        val newContent = oldContent.subSequence(0, size)
        text = newContent
        return newContent.length - oldContent.length
    }

    fun getCharNum(data : Int = getLineNum()) : Int {
        Log.e("TextViewNovel", "getLineNum = " + getLineNum())
        return layout.getLineEnd(data)
    }

    fun getLineNum() : Int {
        val topOfLastLine = height - paddingTop - paddingBottom - lineHeight
        return layout.getLineForVertical(topOfLastLine)
    }

}